package com.spyu.utils;

import java.util.Base64;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;

/**
 * HTTP工具类
 *
 * @author spyu
 * @date 2023-03-08
 */
public class HttpUtils {

    /**
     * 获取HttpServletRequest中的请求体并且转为json字符串
     *
     * @param request 请求
     * @param charset json串编码
     * @return
     */
    public static String getServletJsonBody(HttpServletRequest request, Charset charset) {
        int contentLength = request.getContentLength();
        byte[] buffer = new byte[contentLength];

        try (InputStream inputStream = request.getInputStream()) {
            while (-1 != inputStream.read(buffer)) {

            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new String(buffer, charset);
    }

    /**
     * 给报文进行base64编码
     *
     * @param arr
     * @return
     */
    public static byte[] encodeForBase64(byte[] arr) {
        byte[] encodeArr = Base64.getEncoder().encode(arr);
        return encodeArr;
    }

    /**
     * 给报文进行base64解码
     *
     * @param arr
     * @return
     */
    public static byte[] decodeForBase64(byte[] arr) {
        byte[] decodeArr = Base64.getDecoder().decode(arr);
        return decodeArr;
    }

    /**
     * 给报文进行url编码
     *
     * @param content
     * @param charset
     * @return
     */
    public static String encodeForUrl(String content, String charset) {
        try {
            String encodeStr = URLEncoder.encode(content, charset);
            return encodeStr;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 给报文进行ur解码
     *
     * @param content
     * @param charset
     * @return
     */
    public static String decodeForUrl(String content, String charset) {
        try {
            String decodeStr = URLDecoder.decode(content, charset);
            return decodeStr;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 读取Http请求中请求体的数据
     * @param request
     * @return
     */
    public static byte[] getHttpBody(HttpServletRequest request) {
        byte[] arr = new byte[request.getContentLength()];
        try (InputStream inputStream = request.getInputStream()) {
            while (-1 != inputStream.read(arr)) {

            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return arr;
    }
}
